// 用户信息管理工具
import { ElMessage } from 'element-plus'

export interface UserInfo {
  userId: number | string
  username: string
  realName: string
  role?: string
  userType?: string
  token?: string
}

export class UserManager {
  // 保存用户信息
  static saveUserInfo(userData: UserInfo): void {
    try {
      // 保存完整的用户数据
      localStorage.setItem('user', JSON.stringify(userData))
      
      // 单独保存常用字段
      localStorage.setItem('userId', String(userData.userId))
      localStorage.setItem('username', userData.username)
      localStorage.setItem('realName', userData.realName)

      if (userData.role) {
        localStorage.setItem('role', userData.role)
      }

      if (userData.userType) {
        localStorage.setItem('userType', userData.userType)
      }

      if (userData.token) {
        localStorage.setItem('token', userData.token)
      }
      
      console.log('用户信息已保存')
    } catch (error) {
      console.error('❌ 保存用户信息失败:', error)
    }
  }

  // 获取用户信息字段
  static getUserField(field: keyof UserInfo): string {
    // 首先尝试从单独保存的字段获取
    const directValue = localStorage.getItem(field)
    if (directValue) {
      return directValue
    }

    // 如果没有，尝试从用户JSON对象中获取
    try {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const userData: UserInfo = JSON.parse(userStr)
        return String(userData[field] || 'system')
      }
    } catch (error) {
      console.warn('解析用户数据失败:', error)
    }

    return 'system'
  }

  // 获取完整用户信息
  static getUserInfo(): UserInfo | null {
    try {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        return JSON.parse(userStr)
      }
    } catch (error) {
      console.warn('解析用户数据失败:', error)
    }
    return null
  }

  // 检查用户是否已登录
  static isLoggedIn(): boolean {
    const token = localStorage.getItem('token')
    const user = this.getUserInfo()
    return !!(token && user)
  }

  // 清除用户信息
  static clearUserInfo(): void {
    localStorage.removeItem('user')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    localStorage.removeItem('realName')
    localStorage.removeItem('role')
    localStorage.removeItem('userType')
    localStorage.removeItem('token')
    console.log('用户信息已清除')
  }



  // 获取用户角色
  static getUserRole(): string {
    const role = this.getUserField('role')
    if (role && role !== 'system') {
      return role
    }

    const userType = this.getUserField('userType')
    if (userType && userType !== 'system') {
      return userType
    }

    return '普通用户'
  }

  // 获取操作人信息（用于记录操作日志）
  static getOperator(): string {
    const realName = this.getUserField('realName')
    if (realName && realName !== 'system') {
      return realName
    }

    const username = this.getUserField('username')
    if (username && username !== 'system') {
      return username
    }

    return 'system'
  }
}
